package cn.geminis.workflow.service.service.model;

import cn.geminis.auth.context.LoginUser;
import cn.geminis.workflow.service.entity.ApproveResult;
import cn.geminis.workflow.service.entity.filter.ApproveResultFilter;
import cn.geminis.workflow.service.entity.repository.ApproveResultRepository;
import lombok.RequiredArgsConstructor;
import org.flowable.engine.ProcessEngine;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author puddi
 */
@Service
@RequiredArgsConstructor
public class ApproveResultService {

    private final ProcessEngine engine;
    private final ApproveResultRepository repository;

    public void saveApprove(ApproveResult approveInfo) {
        var taskService = engine.getTaskService();
        taskService.setAssignee(approveInfo.getTaskInstanceId(), LoginUser.fullName());
        this.repository.save(approveInfo);
    }

    public void deleteApprove(String processInstanceId) {
        this.repository.deleteByProcessInstanceId(processInstanceId);
    }

    public Optional<ApproveResult> getByTaskInstanceId(String taskInstanceId) {
        var filter = ApproveResultFilter.builder()
                .taskInstanceId(taskInstanceId);
        return this.repository.findOne(filter.build());
    }

    public List<ApproveResult> findByProcessInstanceId(String processInstanceId) {
        var filter = ApproveResultFilter.builder()
                .processInstanceId(processInstanceId);
        return this.repository.findAll(filter.build());
    }

    public List<ApproveResult> findByTaskIds(String[] taskIds) {
        var filter = ApproveResultFilter.builder()
                .taskInstanceIdIn(taskIds)
                .build();
        return this.repository.findAll(filter);
    }
}
